package org.spbsu.squaddie;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.spbsu.squaddie.model.Cell;
import org.spbsu.squaddie.model.Event;
import org.spbsu.squaddie.model.Snapshot;
import org.spbsu.squaddie.model.TimeSerie;

public class Worker {

	public List<TimeSerie> scanFolder(String folderName) {

		List<TimeSerie> result = new ArrayList<>();

		File folder = new File(folderName);
		
		if (!folder.isDirectory()) {
			System.out.println("The file is not a folder.");
			return result;
		}

		for (File file : folder.listFiles()) {
			if (file.isFile() && !file.isHidden()) {
				TimeSerie timeSerie = getTimeSerie(file);

				result.add(timeSerie);
			}
		}

		return result;
	}

	public TimeSerie getTimeSerie(File seriesFile) {
		TimeSerie result = new TimeSerie();

		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new FileReader(seriesFile));
			String line;

			Integer counter = 0;
			while ((line = reader.readLine()) != null) {
				if (counter++ > 0) {
					Snapshot snapshot = getSnapshot(line); 
					result.add(snapshot);
				}
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				reader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return result;
	}

	public Snapshot getSnapshot(String input) {
		Snapshot result = new Snapshot();
		String[] lines = input.split(" ");

		result.setTime(Long.parseLong(lines[37]));
		result.setMatched(Double.parseDouble(lines[0]));

		for (int i = 0; i < 3; ++i) {
			Event event = new Event();
			for (int j = i * 6; j < 6 + i * 6; ++j) {
				event.add(new Cell(Double.parseDouble(lines[j + 1]), Double
						.parseDouble(lines[j + 1 + 18])));
			}
			
			result.add(event);
		}

		return result;
	}
}
